"""
__author__ = '霍格沃兹测试开发学社'
__desc__ = '更多测试开发技术探讨，请访问：https://ceshiren.com/t/topic/15860'
"""
import time

import requests
from flask import Blueprint, jsonify, request
from sqlalchemy.orm import sessionmaker

from model.sqlalchemy_base import Task, engine,TestCase
from utils.log_util import logger

task_bp = Blueprint('task', __name__, url_prefix='/zijie/task')


@task_bp.route('/update', methods=['POST'])
def update():
    resp = {
        "code": 0,
        "msg": "更新成功！",
        "data": []
    }

    try:

        # 解析请求数据
        req_data = request.json
        logger.info('================================')
        logger.info(req_data)

        # 查询对象
        case_id = req_data.get('id')
        db_session = sessionmaker(bind=engine)()
        case = db_session.query(Task).filter_by(id=case_id).first()
        logger.info('================================')
        logger.info(case)
        # 修改模型对象
        case.name = req_data.get('name')
        case.success = req_data.get('success')
        case.total = req_data.get('total')


        # 提交事务
        db_session.commit()
        db_session.close()

    except Exception as e:
        logger.warning(e)
        resp = {
            "code": -1,
            "msg": f"更新失败，原因：{e}"
        }

    return jsonify(resp)


@task_bp.route('/delete', methods=['POST'])
def delete():


    try:
        # 解析请求数据
        req_data = request.args
        case_id = req_data.get('id')

        # 查询模型对象
        db_session = sessionmaker(bind=engine)()
        case = db_session.query(Task).filter_by(id=case_id).first()

        # 删除
        db_session.delete(case)

        db_session.commit()
        db_session.close()

        resp = {
            "code": 0,
            "msg": "删除成功！"
        }
    except Exception as e:
        logger.warning(e)
        resp = {
            "code": -1,
            "msg": f"删除失败，原因：{e}"
        }

    return jsonify(resp)










@task_bp.route('/add', methods=['POST'])
def add():
    try:
        # 解析请求数据
        req_data = request.json

        # 实例化模型对象
        new_task = Task(
            name=req_data.get('name'),
            success=req_data.get('success'),
            total=req_data.get('total'),
            rate=req_data.get('rate')
        )

        # 写入数据库
        db_session = sessionmaker(bind=engine)()
        db_session.add(new_task)

        db_session.commit()
        db_session.close()

        resp = {
            "code": 0,
            "msg": "新增成功！"
        }

    except Exception as e:
        logger.warning(e)
        resp = {
            "code": -1,
            "msg": f"新增失败，原因：{e}"
        }

    return jsonify(resp)


@task_bp.route('/list', methods=['GET'])
def list():
    try:

        # 查询全部数据
        db_session = sessionmaker(bind=engine)()
        tasks = db_session.query(Task).all()
        task_list = []
        for task in tasks:
            task_dict = task.as_dict()
            task_dict['rate'] = f'{task_dict["rate"]:.2%}'
            task_list.append(task_dict)

        resp = {
            "code": 0,
            "msg": "查询成功！",
            "data": task_list
        }
    except Exception as e:
        logger.warning(e)
        resp = {
            "code": -1,
            "msg": f"查询失败，原因：{e}"
        }

    return jsonify(resp)


@task_bp.route('/execute', methods=['POST'])
def execute():

    try:
        # 解析请求数据
        req_data = request.json
        case_ids: list = req_data.get('ids')
        logger.info(case_ids)
        # 查询测试用例
        db_session = sessionmaker(bind=engine)()

        data = []
        success_count = 0
        for case_id in case_ids:
            print(f'case_id: {case_id}, {type(case_id)}')
            case: TestCase = db_session.query(TestCase).filter_by(id=case_id).first()


            # 发送请求
            r = requests.request(method=case.method,
                                 url=case.url,
                                 params=case.params,
                                 data=case.data)
            if r.status_code == 200:
                success_count += 1
                data.append({'id': case_id, 'result': r.json()})

        # 示例任务模型对象
        new_task = Task(
            name=f'测试任务_{int(time.time())}',
            success=success_count,
            total=len(case_ids),
            rate=round(success_count/len(case_ids), 2)
        )

        # 新增任务表记录
        db_session.add(new_task)

        db_session.commit()
        db_session.close()

        resp = {
            "code": 0,
            "msg": "执行成功！",
            "data": data
        }
    except Exception as e:
        logger.warning(e)
        resp = {
            "code": -1,
            "msg": f"查询失败，原因：{e}"
        }

    return jsonify(resp)
